use warnings;
use strict;

sub TheTVDb {
	my ($title, $episode, $tvdb_id, $edit, $re) = @_ ;
	my $record;
	my $count = 0;
	my $ep_id = '';
	if ($episode =~ m!s0?(\d+)e(\d+)(?:-\d+)?!){ 
		$episode = $1.$2;
		#my $s = $1;
		#$episode = $2;
		#$episode = $s.$2; 
	}
	if ($title eq 'Pawn Stars'){ 
		$episode = ($episode - 242);#$s =~ tr/5-9/3-7/; } # 368 = 608 240
	}
	
	# FULL show/eps record: check
	if (-e "$VAR{'PPWebDir'}/data/tvdb/$title.txt"){# want $edit = list, $edit = short title OK - don't have id much less a file
		open (RDB, "<$VAR{'PPWebDir'}/data/tvdb/$title.txt") or &Print ("  Couldn't open $VAR{'PPWebDir'}/data/tvdb/$title.txt, $! (TV01)", 1, 0);
		while (<RDB>){
			# show id/record
			if (m!^(\d+)\t(.+)!){ 
				$tvdb_id = $1;
				my $rec = "$2\n";
				#&Print ("TVDb id found (cached): $title (TV01)", 5, 0);
				&Print ("TVDb show/ep record found (cached): $title (TV01)", 4, 0);
				# id is all we need for existing base record or edit del/up
				unless (($episode and $episode =~ m!^\d!) or $edit eq 'list'){ 
					$record = $rec;
					#&Print ("TVDb base record found (cached): $title (TV01)", 3, 0);
					last; 
				}
			}
			# date based ep id/date
			elsif ($episode and m!^(\d+) \d+\t([^\t]+\t1st Aired\.: 20$episode<br>\t.+)!){
				$ep_id = $1;
				$record = "$2\n";
				&Print ("TVDb date based episode record found (cached): $title $episode (TV01)", 4, 0);
				last;
			}
			# ep id/num
			elsif ($episode and m!^(\d+) $episode\t(.+)!){ 
				# should have ep var also?
				$ep_id = $1;
				$record = "$2\n";
				&Print ("TVDb episode record found (cached): $title $episode (TV01)", 4, 0);
				last;
			}
			# full record for list eps option
			elsif (m!^[^\t]+\t(.+?)[^>]*$!){	
				$record .= "$1\n";
				#&Print ("TVDb episode list record found (cached): $title (TV01)", 3, 0);
			}
		}
		close RDB or warn $!;
		
		# auto update if no requested ep
		if ($episode and $episode =~ m!^\d! and !$ep_id){
			#&Print ("Getting TVDb (id: $tvdb_id) episode: $title $episode (TV02)", 4, 0);
			($record, $tvdb_id, $count, $edit) = GetTvdb ($title, $episode, $tvdb_id, $edit, $re, 'eps')
			#($record, $tvdb_id, $count, $edit) = GetTvdb ($title, $episode, $tvdb_id, $edit, $re, 'ep')
		}
		# update
		elsif ($edit eq 'up'){
			&Print ("Updating TVDb (id: $tvdb_id) episode list: $title (TV03)", 4, 0);
			($record, $tvdb_id, $count, $edit) = GetTvdb ($title, $episode, $tvdb_id, $edit, $re, 'eps')
		}
		# delete
		elsif ($tvdb_id and $edit eq 'del'){
			&Print ("Deleting TVDb episode record: $title (TV04)", 4, 0);
			&Delete ("$VAR{'PPWebDir'}/data/tvdb", "$title.txt", 'TV06');
			if (-e "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id.jpg"){ &Delete ("$VAR{'PPWebDir'}/data/tvdb/images", "$tvdb_id.jpg", 'TV07'); }
		}		
	}
	# FULL show/eps record: get
	elsif ($episode or $edit eq 'list'){
		unless ($tvdb_id) { 
			# check BASE record for id (quicker then TVDb lookup?)
			open (RDB, "<$VAR{'DataDir'}/ppweb_tvdb.txt") or &Print ("  Couldn't open $VAR{'DataDir'}/ppweb_tvdb.txt, $! (TV08)", 1, 0);
			while (<RDB>){ # show id/title
				if (m!^(\d+) $title\t!){
					$tvdb_id = $1;
					&Print ("TVDb id found (cached): $title (TV08)", 4, 0);
					last;
				}
			}
			close RDB or warn $!;
# 			local ($^I, @ARGV) = ('', "$VAR{'DataDir'}/ppweb_tvdb.txt");
# 			while(<>){
# 				if (m!^(\d+) $title\t!){ 
# 					$tvdb_id = $1;
# 					next; # delete the unneeded record 
# 				}
# 				else { print; }
# 			}
		}
		&Print ("Fetching TVDb episode record: $title (TV09)", 4, 0);
		($record, $tvdb_id, $count, $edit) = GetTvdb ($title, $episode, $tvdb_id, $edit, $re, 'eps')
	}
	# BASE records
	elsif (-e "$VAR{'DataDir'}/ppweb_tvdb.txt"){ 
		# see if we have a base record
		open (RDB, "<$VAR{'DataDir'}/ppweb_tvdb.txt") or &Print ("  Couldn't open $VAR{'DataDir'}/ppweb_tvdb.txt, $! (TV12)", 1, 0);
		while (<RDB>){ # show id/title
			if (m!^(\d+) $title\t(.+)!){
				$tvdb_id = $1;
				$record = "$2\n";
				&Print ("TVDb base record (cached) found for $title (TV12)", 4, 0);
				last;
			}
		}
		close RDB or warn $!;
		
		if (!$record or $edit eq 'up'){
			($record, $tvdb_id, $count, $edit) = GetTvdb ($title, $episode, $tvdb_id, $edit, $re, 'base')
		}
		elsif ($tvdb_id and $edit eq 'del'){
			&Print ("Deleting TVDb base record: $title (TV16)", 4, 0);
			local ($^I, @ARGV) = ('', "$VAR{'DataDir'}/ppweb_tvdb.txt");
			while(<>){
				if (m!^$tvdb_id!){ next; } # edit del
				else { print; }
			}
			if (-e "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id.jpg"){ &Delete ("$VAR{'PPWebDir'}/data/tvdb/images", "$tvdb_id.jpg", 'TV17'); }
		}		
	}
	
	# print record
	if ($edit eq 'del'){ 
		$record = "<pre><font face=\"Monospace,Courier,Courier New\">Record Deleted</font></pre></td></tr><tr><td>";
	}
	elsif ($record){ 
		$record = &PrintTvdb ($record, $count, $title, $episode, $tvdb_id, $edit, $re);
	}
# 		my $imdb = '';
# 		$record =~ s!<br>\t?!\n!g;
# 		# multiple parent possibilities
# 		if ($count > 1){
# 			$record =~ s!(tt\d+)!Links.....: <A HREF=\"http://www.imdb.com/title/$1/\">IMDb</A>\n!g;
# 			$record =~ s!\w{3} \d{2} \d{4}!!g;
# 			$record =~ s!(\d+)\tTitle.....: ([^\n]+)!Title.....: [<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=$episode&amp;id=$1&amp;db=&amp;re=$re\">$2</a>]!g;
# 			# shouldn't it be
# 			#$record =~ s!(\d+) [^\n]+\tTitle.....: ([^\n]+)!Title.....: [<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=$episode&amp;id=$1&amp;db=&amp;re=$re\">$2</a>]!g;
# 			$record = "Multiple matches found, please select one of the following titles:\n\n$record";
# 			$record = "<pre><font face=\"Monospace,Courier,Courier New\">$record</font></pre></td></tr><tr><td>";
# 		}
# 		# parent records only
# 		elsif ($record =~ s!(\w{3} \d{2} \d{4})(tt\d+)?$!!){ 
# 			if ($2){ $imdb = "&nbsp;&nbsp;<A HREF=\"http://www.imdb.com/title/$2/\">IMDb</A>&nbsp"; }
# 			$record .= "Links.....: <A HREF=\"http://thetvdb.com/?tab=series&id=$tvdb_id\">TVDb</A>&nbsp;$imdb&nbsp;&nbsp;Record:&nbsp;<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=$episode&amp;id=$tvdb_id&amp;db=del&amp;re=$re\">delete</a>&nbsp;<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=$episode&amp;id=$tvdb_id&amp;db=up&amp;re=$re\">update</a>\n\n$1\n";
# 			if (-e "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id.jpg"){
# 				$record = "<img SRC=\"$VAR{'PPWebUrl'}/data/tvdb/images/$tvdb_id.jpg\" style=\"float:right\; padding-right:50px;\"><pre><font face=\"Monospace,Courier,Courier New\">\n$record</font></pre><br clear=\"all\"></td></tr><tr><td>";
# 			}
# 			else { $record = "<pre><font face=\"Monospace,Courier,Courier New\">$record</font></pre></td></tr><tr><td>"; }
# 		}
# 		# episode records
# 		elsif ($episode and $record =~ s!(\w{3} \d{2} \d{4})(JPG)?/$tvdb_id/(\d+)/(\d+)(tt\d+)?$!!){
# 			if ($5){ $imdb = "&nbsp;&nbsp;<A HREF=\"http://www.imdb.com/title/$5/\">IMDb</A>&nbsp"; }
# 			$record .= "Links.....: <A HREF=\"http://thetvdb.com/?tab=episode&amp;seriesid=$tvdb_id&amp;seasonid=$3&amp;id=$4\">TVDb</A>&nbsp;$imdb&nbsp;&nbsp;Record:&nbsp;<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=$episode&amp;id=$tvdb_id&amp;db=del&amp;re=$re\">delete</a>&nbsp;<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=$episode&amp;id=$tvdb_id&amp;db=up&amp;re=$re\">update</a>&nbsp;&nbsp;&nbsp;View:&nbsp;<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=&amp;id=$tvdb_id&amp;db=list&amp;re=$re\">list</a>&nbsp;<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=&amp;id=$tvdb_id&amp;db=&amp;re=$re\">parent</a>\n\n$1\n";
# 			if (-e "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id\_$4.jpg"){
# 				$record = "<img SRC=\"$VAR{'PPWebUrl'}/data/tvdb/images/$tvdb_id\_$4.jpg\" style=\"float:right\; padding-right:50px;\"><pre><font face=\"Monospace,Courier,Courier New\">\n$record</font></pre><br clear=\"all\"></td></tr><tr><td>";
# 			}
# 			elsif (-e "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id.jpg"){
# 				$record = "<img SRC=\"$VAR{'PPWebUrl'}/data/tvdb/images/$tvdb_id.jpg\" style=\"float:right\; padding-right:50px;\"><pre><font face=\"Monospace,Courier,Courier New\">\n$record</font></pre><br clear=\"all\"></td></tr><tr><td>"; 
# 			}
# 			else {
# 				$record = "<pre><font face=\"Monospace,Courier,Courier New\">\n$record</font></pre><br clear=\"all\"></td></tr><tr><td>"; 
# 			}
# 		}
# 		elsif (-e "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id.jpg"){
# 			$record = "<img SRC=\"$VAR{'PPWebUrl'}/data/tvdb/images/$tvdb_id.jpg\" style=\"float:right\; padding-right:50px;\"><pre><font face=\"Monospace,Courier,Courier New\">\n$record</font></pre><br clear=\"all\"></td></tr><tr><td>";
# 		}
# 		elsif ($record eq 'No matches found' and $edit){
# 			$record = "<pre><font face=\"Monospace,Courier,Courier New\">No matches found, try [<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=$episode&amp;id=&amp;db=$edit&amp;re=$re\">$edit</a>]</font></pre></td></tr><tr><td>";
# 		}
# 		elsif ($record eq 'No matches found' and $title =~ m!(.+) [^ ]+$!){
# 			$record = "<pre><font face=\"Monospace,Courier,Courier New\">No matches found, try [<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=$episode&amp;id=&amp;db=$1&amp;re=$re\">$1</a>]</font></pre></td></tr><tr><td>";
# 		}
# 		else { $record = "<pre><font face=\"Monospace,Courier,Courier New\">$record</font></pre></td></tr><tr><td>"; }
# 	}
	else { $record = "<pre><font face=\"Monospace,Courier,Courier New\">Unable to fetch record</font></pre></td></tr><tr><td>";}
	
	return $record;
}

sub GetTvdb {
	my ($title, $episode, $tvdb_id, $edit, $re, $type) = @_ ;
	my $api = 'D192BBDD2E810B5C';
	my $record = '';
	my $ep_id;
	my $count = 0;
	my $ep_rec;
	my $url;
	my $response;
	my $no_rec = 0;
	
	require LWP::UserAgent;
	my $user_agent = LWP::UserAgent->new;
	$user_agent->agent("Mozilla/8.1");
	
	unless ($tvdb_id){
		# try lookup with shortened title - full title lookup failed
		if ($edit and $edit ne 'list'){ # del and up require $tvdb_id... so does list ATM
			$url = "http://thetvdb.com/api/GetSeries.php?seriesname=$edit";
			if ($edit =~ m!(.+) [^ ]+$!){ $edit = $1; }
			else { $edit = ''; }
		}
		# standard lookup
		else { $url = "http://thetvdb.com/api/GetSeries.php?seriesname=$title"; }
		$response = $user_agent->get($url);
		if ($response->is_success and $response->decoded_content) {
			my @xml = split (/[\r\n]+/, $response->decoded_content);
			# is $tvdb_id when don't have one, otherwise its $ep_id (which can be the same as $tvdb_id)
			($record, $tvdb_id, $count, $ep_rec) = &ParseTvdb (\@xml, $user_agent, $tvdb_id, $title, $episode);
			if ($tvdb_id){
				&Print ('Got TVDb id ('.$tvdb_id.') for '.$title.' (TV40)', 5, 0);
			}
			elsif (!$record){ $no_rec = 1; }
		}
		else { &Print ('TVDb id lookup for '.$title.' failed: '.$response->status_line.' (TV40)', 1, 0); }
	}
	if ($tvdb_id and $count <= 1){
		if ($type eq 'ep'){
			if ($episode =~ m!\d{2}-\d{2}-\d{2}!){ 
				#&Print ('Fetching TVDb date based episode record for '.$title.' '. $episode.' (TV41)', 3, 0);
				$url = "http://thetvdb.com/api/GetEpisodeByAirDate.php?apikey=$api&seriesid=$tvdb_id&airdate=20$episode&language=en";
			}
			elsif ($episode =~ m!(\d+)(\d{2})$!){
				my $s = $1; # no ^0 this sub
				my $ep = $2;
				$ep =~ s!^0!!;
				#&Print ('Fetching TVDb episode record for '.$title.' '. $episode.' (TV41)', 3, 0);
				$url = "http://thetvdb.com/api/$api/series/$tvdb_id/default/$s/$ep/en.xml";
				#&Print ("TVDb ep URL:$url (TV43)", 5, 0);
			}
			if ($url){
				$response = $user_agent->get($url);
				if ($response->is_success and $response->decoded_content) { 
					my @xml = split (/[\r\n]+/, $response->decoded_content);
					($record, $tvdb_id, $count, $ep_rec) = &ParseTvdb (\@xml, $user_agent, $tvdb_id, $title, $episode);
					if ($record){
						unless ($record eq 'No matches found'){
							&Print ('Got TVDb episode record for '.$title.' '. $episode.' (TV41)', 4, 0);
							open (WDB, ">>$VAR{'PPWebDir'}/data/tvdb/$title.txt") or &Print ("  Couldn't open $VAR{'PPWebDir'}/data/tvdb/$title.txt, $! (TV41)", 1, 0);
								print WDB $record;
							close WDB or warn $!;
						}
						$record =~ s!^[^\t]+\t!!; # remove leading id and title
					}
					else { $no_rec = 1; }
				}
				else { &Print ('TVDb episode fetch for '.$title.' '. $episode.' failed: '.$response->status_line.' (TV41)', 1, 0); }
			}
			else { &Print ("TVDb episode ($episode) parse failed for $title (TV41)", 2, 0); }
		}
		elsif ($type eq 'eps'){
			&TvdbZip ($tvdb_id, $title, $api, $user_agent);
			if (-e "$VAR{'PPWebDir'}/data/tvdb/$tvdb_id.xml"){
				open (RDB, '<:encoding(utf8)', "$VAR{'PPWebDir'}/data/tvdb/$tvdb_id.xml") or &Print ("  Couldn't open $VAR{'PPWebDir'}/data/tvdb/$tvdb_id.xml, $! (TV42)", 1, 0);
				my @xml = <RDB>;
				close RDB or warn $!;
				# comment out to save/reuse
				&Delete ("$VAR{'DataDir'}/tvdb", "$tvdb_id.xml", 'TV42');
				($record, $ep_id, $count, $ep_rec) = &ParseTvdb (\@xml, $user_agent, $tvdb_id, $title, $episode);
				if ($record){
					&Print ("Got full TVDb episode record for $title (TV43)", 4, 0);
					open (WDB, ">$VAR{'PPWebDir'}/data/tvdb/$title.txt") or &Print ("  Couldn't open $VAR{'PPWebDir'}/data/tvdb/$title.txt, $! (TV42)", 1, 0);
						print WDB $record;
					close WDB or warn $!;
					$record =~ s!^[^\t]+\t!!; # remove leading id and title
					if ($ep_rec and $edit eq 'up'){ $record = "Record Updated\n\n$ep_rec"; }
					elsif ($ep_rec){ $record = $ep_rec; }
					#elsif ($ep_rec and $edit ne 'list'){ $record = $ep_rec; }
				}
				else { &Print ('TVDb record parsing failed for '.$title.' file: '.$VAR{'DataDir'}.'/tvdb/'.$tvdb_id.'.xml (TV42)', 1, 0); }
			}
		}
		elsif ($type eq 'base'){
			$url = "http://thetvdb.com/api/$api/series/$tvdb_id/en.xml";
			$response = $user_agent->get($url);
			if ($response->is_success and $response->decoded_content) { 
				my @xml = split (/[\r\n]+/, $response->decoded_content);
				($record, $ep_id, $count, $ep_rec) = &ParseTvdb (\@xml, $user_agent, $tvdb_id, $title, $episode);
				if ($record){
					&Print ("Got TVDb base record for $title (TV43)", 4, 0);
					# add our title to lead, parse/body title is tvdb title
					$record =~ s!^(\d+)!$1 $title!;
					if ($edit eq 'up'){
						local ($^I, @ARGV) = ('.bak', "$VAR{'DataDir'}/ppweb_tvdb.txt");
						while(<>){
							if ($. == 1) { 
								print $record; # updated record
								unless (m!^$tvdb_id!){ print; } # replaced record on 1st line
							}
							elsif (m!^$tvdb_id!){ next; } # replaced record elsewhere
							else { print; }
						}
					}
					else {
						open (WDB, ">>$VAR{'DataDir'}/ppweb_tvdb.txt") or &Print ("  Couldn't open $VAR{'DataDir'}/ppweb_tvdb.txt, $! (TV43)", 1, 0);
							print WDB $record;
						close WDB or warn $!;
					}
					$record =~ s!^[^\t]+\t!!; # remove leading id and title for print
					if ($ep_rec and $edit eq 'up'){ $record = "Record Updated\n\n$ep_rec"; }
				}
				else { $no_rec = 1; }
			}
			else { &Print ('TVDb record fetch failed for '.$title.': '.$response->status_line.' (TV43)', 1, 0); }
		}
	}
	if ($no_rec and $response){
		&Print ("TVDb record parsing failed, writing TVDb response to $VAR{'DataDir'}/response_tvdb.txt (TV44)", 1, 0);
		open (WDB, ">$VAR{'DataDir'}/response_tvdb.txt") or &Print ("  Couldn't open $VAR{'DataDir'}/response_tvdb.txt, $! (TV44)", 1, 0);
			print WDB $response->headers_as_string;
			print WDB $response->decoded_content;
		close WDB or warn $!;
	}
	return ($record, $tvdb_id, $count, $edit);
}

sub TvdbZip {
	my ($tvdb_id, $title, $api, $user_agent) = @_ ;
	# for dev, keep/reuse xml file
	#unless (-e "$VAR{'PPWebDir'}/data/tvdb/$tvdb_id.xml"){
		my $url = "http://thetvdb.com/api/$api/series/$tvdb_id/all/en.zip";
		my $response = $user_agent->get($url, ':content_file' => "$VAR{'PPWebDir'}/data/tvdb/$tvdb_id.zip");
		if ($response->is_success) {
			open (ARCHIVE, "-|", "$VAR{'Unzip'} -jo \"$VAR{'PPWebDir'}/data/tvdb/$tvdb_id.zip\" -d \"$VAR{'PPWebDir'}/data/tvdb\"") or &Print ("  Couldn't open: $VAR{'Unzip'}, $! (TV47)", 1, 0);
			while (<ARCHIVE>){ 
				if (m!([^/]+)/en.xml  (?:.+OK )?$!i){
					&Print ("  Extracted: $1/en.xml (TV48)", 5, 0);
				}
				elsif (m!([^/]+\.[^\.]{3,4})  (?:.+OK )?$!){
					&Delete ("$VAR{'PPWebDir'}/data/tvdb", $1, 'TV49');
				}
			}
			close ARCHIVE or warn $?;
			&Delete ("$VAR{'PPWebDir'}/data/tvdb", "$tvdb_id.zip", 'TV50');
			# for dev
			&Save ("$VAR{'PPWebDir'}/data/tvdb", 'en', 'xml', "$VAR{'PPWebDir'}/data/tvdb", $tvdb_id, 'xml', 'TV51');
		}
		else { &Print ('TVDb record fetch failed for '.$title.': '.$response->status_line.' (TV52)', 1, 0); }
	#}
}

sub ParseTvdb {
	my ($xml, $user_agent, $tvdb_id, $show, $episode) = @_ ;
	my ($s_id, $ep_id, $ep_num, $actors, $rated, $first_aired, $genre, $IMDb, $plot, $rating, $votes, $title, $status, $director, $writer, $rec_tail) = ('') x 16;
	my $count = 0;
	my $record = ''; 
	my $ep_rec = '';
	my $s_num = 0;
	foreach (@$xml){
		chomp;
		# utf8 > &#nnn;
		s/([^\x20-\x7F])/'&#'.ord($1).';'/gse;
		
		# for show and ep ids (same match)
		if (m!^ *<id>(\d+)</id>!){
			$ep_id = $1;
			# only gets written in series block and only gets filled once
			unless ($tvdb_id){$tvdb_id = $1}
		} 
		elsif (m!^ *<EpisodeNumber>(\d+)</EpisodeNumber>!){
			$ep_num = $1;
			unless ($ep_num =~ m!\d\d!){ $ep_num = "0$ep_num"; }
		}
		elsif (m!^ *<SeasonNumber>(\d+)</SeasonNumber>!){
			# year to +1 season per year
			if ($1 =~ m!\d{4}! and $ep_num == 1){ $s_num ++; }
			if ($s_num){ $ep_num = "$s_num$ep_num"; }
			# std num
			else { $ep_num = "$1$ep_num"; }
		}
		elsif (m!^ *<seasonid>(\d+)</seasonid>!){
			$s_id = $1;
		}
		
		# title - show and ep
		elsif (m!^ *<SeriesName>([^<]*)</SeriesName>!){
			# leave series name alone, no need to change
			$title = "Title.....: $1<br>\t";
		}
		elsif (m!^ *<EpisodeName>([^<]*)</EpisodeName>!){
			$title = $1;
			$title =~ s! &(?:amp;)? ! and !; # others to keep/change?
			$title =~ s! @ ! at !;
			$title =~ s!&#?\w+;!!g; # &nbsp;. &#nnn; etc.
			#$title =~ s!&#\d+;!!g; # all wide chars (utf8 conv at top), would be nice to convert to ASCII
			#$title =~ s!(\w)\.(\w)\.!$1$2!; # M.D. J.D. P.S...
			$title =~ s!\b[=&.+*#]\b! !g; # replace w/ space
			$title =~ s! *[/,;-] *!-!g; # chained names
			$title =~ s![=&..+*#,@\!/?:;()"'\$\\]!!g; # del all not handled above
			#$title =~ s!\b\W\b!!g; # del all non word characters
			#$title =~ s! ?\W ?! !g; # del all non word characters
			#$title =~ s!\b\W\b! !g; # replace w/ space
			#$title =~ s! = ! Equals !;
			#$title =~ s! ?[/,;-] ?!-!; # chained names
			#$title =~ s!\b[.*#]\b! !g;
			#$title =~ s!(\w)[.*#](\w)!$1 $2!g; # changed to \b
			#$title =~ s![=&/]! !g; # assume \b?... added to \b
			#my $title = Encode::encode("ISO-8859-1", $item->{title});
			#$title =~ s/[^[:ascii:]]+//g;
			
			# remove extra spaces
			$title =~ s! +! !g;
			$title =~ s!^[\t ]+!!; # known ^\t
			$title =~ s![\t ]+$!!; # no known \t$
			
			# do after weed out unwanted titles
			#$title = "Title.....: $title<br>\t";
		}
		# first aired - show and ep
		elsif (m!^ *<FirstAired>([^<]*)</FirstAired>!){$first_aired = $1;}
		# director - ep
		elsif (m!^ *<Director>\|?([^<]*?)\|?</Director>!){
			$director = $1;
			$director =~ s!^ *(.+?) *$!$1!g;
			$director =~ s!\|!, !g;
			$director =~ s!([^\n]{55,65} )!$1<br>            !g;
			$director="Director..: $director<br>\t";
		}
		# writer - ep
		elsif (m!^ *<Writer>\|?([^<]*?)\|?</Writer>!){
			$writer = $1;
			$writer =~ s!^ *(.+?) *$!$1!g;
			$writer =~ s!\|!, !g;
			$writer =~ s!([^\n]{55,65} )!$1<br>            !g;
			$writer="Writer....: $writer<br>\t";
		}
		# actors 
		elsif (m!^ *<Actors>\|?([^<]*?)\|?</Actors>!){
			$actors = $1;
			$actors =~ s!^ *(.+?) *$!$1!g;
			$actors =~ s!\|!, !g;
			$actors =~ s!([^\n]{55,65}, )!$1<br>            !g;
			$actors="Actors....: $actors<br>\t";
		}
		# guests
		elsif (m!^ *<GuestStars>\|?([^<]*?)\|?</GuestStars>!){
			$actors = $1;
			$actors =~ s!^ *(.+?) *$!$1!g;
			$actors =~ s![\|:] ?!, !g;
			$actors =~ s!([^\n]{55,65}, )!$1<br>            !g;
			$actors="Guests....: $actors<br>\t";
		}
		elsif (m!^ *<Rating>([^<]*)</Rating>!){$rating="Rating....: $1<br>\t";}
		elsif (m!^ *<RatingCount>([^<]*)</RatingCount>!){$votes="Votes.....: $1<br>\t";}
		
		elsif (m!^ *<Overview>([^<]*)(?:</Overview>)?!){
			$plot = $1;
			$plot =~ s!&#13;$!!; # unknown char @ EOL 
			$plot =~ s! +! !g;
			$plot =~ s!([^\n]{55,65} )!$1<br>            !g;
			$plot = "Plot......: $plot<br>";
			$plot =~ s![\r\n]+!!g;
		}
		# for lines in between Overview open and close lines
		elsif (m!^(\w[^<>]+)$!){
			my $splot = $1;
			$splot =~ s!&#13;$!!; # unknown char @ EOL 
			$splot =~ s! +! !g;
			$splot =~ s!([^\n]{55,65} )!$1<br>            !g;
			$plot .= "<br>            $splot<br>";
			$plot =~ s![\r\n]+!!g;
		}
		elsif (m!^([^<]*)</Overview>!){
			#my $splot = "<br>            $1";
			my $splot .= $1;
			$splot =~ s!&#13;$!!; # unknown char @ EOL 
			$splot =~ s! +! !g;
			$splot =~ s!([^\n]{55,65} )!$1<br>            !g;
			$plot .= "<br>            $splot<br>";
			$plot =~ s![\r\n]+!!g;
		}
		
		# show
		elsif (m!^ *<Status>([^<]*)</Status>!){$status="Status....: $1<br>\t";}
		elsif (m!^ *<ContentRating>([^<]*)</ContentRating>!){$rated="Rated.....: $1<br>\t";}
		elsif (m!^ *<Genre>\|?([^<]*?)\|?</Genre>!){
			$genre = $1;
			$genre =~ s! ?(.+?) ?$!$1!g;
			$genre =~ s!\|!, !g;
			$genre="Genre.....: $genre<br>\t";
		}
		
		elsif (m!^ *<IMDB_ID>([^<]*)</IMDB_ID>!){ $IMDb = $1; }
		# ep screenshot - handled later
		elsif (m!^ *<filename>([^<]*)</filename>$!){
			if ($1){ $rec_tail = 'JPG'; }
		}
		# show poster (small) - ep listings don't have <poster>
		elsif (m!^ *<poster>([^<]+)</poster>$!){
			$rec_tail = "http://thetvdb.com/banners/_cache/$1";
			unless (-e "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id.jpg"){
				my $response = $user_agent->get($rec_tail, ':content_file' => "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id.jpg");
				unless ($response->is_success) {
					&Print ("Image ($1) fetch failed: ".$response->status_line.' (TV60)', 3, 0);
					$rec_tail = "http://thetvdb.com/banners/_cache/posters/$tvdb_id-1.jpg";
					$response = $user_agent->get($rec_tail, ':content_file' => "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id.jpg");
					if ($response->is_success) {
						&Print ("Alternate image fetch successful: posters/$tvdb_id-1.jpg (TV61)", 3, 0);
					}
					else { &Print ("Alternate image ($tvdb_id-1.jpg) fetch also failed: ".$response->status_line.' (TV62)', 1, 0); }
					
				}
			}
		}
		# some unused data fields
		#elsif (m!^ *?<Network>([^<]*)</Network>!){$net="Network...: $1<br>\t";}
		#elsif (m!^ *?<Airs_DayOfWeek>([^<]*)</Airs_DayOfWeek>!){$day="Day.......: $1<br>\t";}
		#elsif (m!^ *?<Airs_Time>([^<]*)</Airs_Time>!){$time="Time......: $1<br>\t";}
		#elsif (m!^ *?<Runtime>([^<]*)</Runtime>!){$run="Runtime...: $1 min<br>\t";}
		#elsif (m!^ *?<Language>([^<]*)</Language>!){$lang="Lang......: $1<br>\t";}
		
		elsif (m!^ *</Series>!){ # needs to be $ep_id for successive matches
			if ($first_aired){ $first_aired = "1st Aired.: $first_aired<br>\t"; }
			$ep_rec = "$title$first_aired$status$rated$genre$actors$rating$votes$plot$DateTime[2]$IMDb\n";
			$record .= "$ep_id\t$title$first_aired$status$rated$genre$actors$rating$votes$plot$DateTime[2]$IMDb\n";
			$count ++;
			# vars that need to be emptied
			$first_aired = ''; $plot = ''; $IMDb = ''; 
		}
		elsif (m!^ *</Episode>!){
			# skip all worthless ep titles and all specials (O season)... but this is used for ep info as well - not just ep titles
			# removed |Season|Episode|Chapter, needed for episode pages (won't be in db otherwise)
			# ... may want to keep Season, may want to remove ^0 - don't really know
			if ($title =~ m!^(TBA|TBD)!i or $ep_num =~m!^0!){ next; }
			#elsif ($title =~ m!^(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)!){ next; }
			elsif ($title) { 
				# ep title > full 'show ep num - ep title'
				#$title =~ s!Title\.\.\.\.\.: (.+)<br>\t!Title.....: $show $ep_num - $1<br>\t!;
				$title = "Title.....: $show $ep_num - $title<br>\t";
				# contains JPG if there's an image
				$rec_tail .= "/$tvdb_id/$s_id/$ep_id";
				#  datetime(JPG)/showid/seasonid/epid(ttnum added later)
				$rec_tail = "$DateTime[2]$rec_tail";
				# for date based ep num/match
				if ($episode =~ m!\d{2}-\d{2}-\d{2}!){ 
					unless ($first_aired){ $first_aired = '00-00-00'; }
					$ep_num = $first_aired; 
					$ep_num =~ s!^(20|19)!!; 
					
				}
				$first_aired = "1st Aired.: $first_aired<br>\t"; # needs to be after above
				# ep match record and image
				if ($ep_num eq $episode){ 
					if ($rec_tail =~ m!JPG/!){
						unless (-e "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id\_$ep_id.jpg"){
							my $url = "http://thetvdb.com/banners/episodes/$tvdb_id/$ep_id.jpg";
							my $response = $user_agent->get($url, ':content_file' => "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id\_$ep_id.jpg");
							unless  ($response->is_success) { &Print ("Image fetch failed: $response->status_line (TV63)", 1, 0); }
						}
					}
					$ep_rec = "$title$first_aired$director$writer$actors$rating$votes$plot$rec_tail$IMDb\n"; 
				}
# 				elsif (!$episode){
# 					$ep_rec .= "$title$first_aired$director$writer$actors$rating$votes$plot\n";
# 				}
				#else { $ep_rec = "$title$first_aired$director$writer$actors$rating$votes$plot$rec_tail$IMDb\n"; }
				$record .= "$ep_id $ep_num\t$title$first_aired$director$writer$actors$rating$votes$plot$rec_tail$IMDb\n"; }
				# vars that need to be emptied
				$rec_tail = '';
		}
		elsif (m!^ *</Data>! and !$record){ $record = 'No matches found'; }
	}
	return ($record, $tvdb_id, $count, $ep_rec);
}

sub ParseXBMC {
	my ($xml, $user_agent, $tvdb_id, $show, $episode) = @_ ;
	my ($s_id, $ep_id, $ep_num, $actors, $rated, $first_aired, $genre, $IMDb, $plot, $rating, $votes, $title, $status, $director, $writer, $rec_tail) = ('') x 16;
	my $count = 0;
	my $record = ''; 
	my $ep_rec = '';
	my $s_num = 0;
	foreach (@$xml){
		chomp;
		# utf8 > &#nnn;
		s/([^\x20-\x7F])/'&#'.ord($1).';'/gse;
		
		# for show and ep ids (same match)
		if (m!^ *<id>(\d+)</id>!){
			$ep_id = $1;
			# only gets written in series block and only gets filled once
			unless ($tvdb_id){$tvdb_id = $1}
			
			#<id>$tvdb_id</id>
			#<episodeguide>
				#<url cache="$tvdb_id.xml">http://www.thetvdb.com/api/1D62F2F90030C444/series/73388/all/en.zip</url>
			#</episodeguide>
		} 
		elsif (m!^ *<EpisodeNumber>(\d+)</EpisodeNumber>!){
			$ep_num = $1;
			unless ($ep_num =~ m!\d\d!){ $ep_num = "0$ep_num"; }
			#<episode>$ep_num</episode>
		}
		elsif (m!^ *<SeasonNumber>(\d+)</SeasonNumber>!){
			# raw for xmbc?
			#<season>$1</season>
			# year check?
			#<year>0</year>
			
			# year to +1 season per year
			if ($1 =~ m!\d{4}! and $ep_num == 1){ $s_num ++; }
			if ($s_num){ $ep_num = "$s_num$ep_num"; }
			# std num
			else { $ep_num = "$1$ep_num"; }
			
			#<season>-1</season>
		}
		elsif (m!^ *<seasonid>(\d+)</seasonid>!){
			$s_id = $1;
		}
		
		# title - show and ep
		elsif (m!^ *<SeriesName>([^<]*)</SeriesName>!){
			# leave series name alone, no need to change
			$title = "Title.....: $1<br>\t";
			
			#(<tvshow>)
			#<title>$title</title>
		}
		elsif (m!^ *<EpisodeName>([^<]*)</EpisodeName>!){
			$title = $1;
			$title =~ s! &(?:amp;)? ! and !; # others to keep/change?
			$title =~ s! @ ! at !;
			$title =~ s!&#?\w+;!!g; # &nbsp;. &#nnn; etc.
			#$title =~ s!&#\d+;!!g; # all wide chars (utf8 conv at top), would be nice to convert to ASCII
			#$title =~ s!(\w)\.(\w)\.!$1$2!; # M.D. J.D. P.S...
			$title =~ s!\b[=&.+*#]\b! !g; # replace w/ space
			$title =~ s! *[/,;-] *!-!g; # chained names
			$title =~ s![=&..+*#,@\!/?:;()"'\$\\]!!g; # del all not handled above
			#$title =~ s!\b\W\b!!g; # del all non word characters
			#$title =~ s! ?\W ?! !g; # del all non word characters
			#$title =~ s!\b\W\b! !g; # replace w/ space
			#$title =~ s! = ! Equals !;
			#$title =~ s! ?[/,;-] ?!-!; # chained names
			#$title =~ s!\b[.*#]\b! !g;
			#$title =~ s!(\w)[.*#](\w)!$1 $2!g; # changed to \b
			#$title =~ s![=&/]! !g; # assume \b?... added to \b
			#my $title = Encode::encode("ISO-8859-1", $item->{title});
			#$title =~ s/[^[:ascii:]]+//g;
			
			# remove extra spaces
			$title =~ s! +! !g;
			$title =~ s!^[\t ]+!!; # known ^\t
			$title =~ s![\t ]+$!!; # no known \t$
			
			# do after weed out unwanted titles
			#$title = "Title.....: $title<br>\t";
			
			#(<episodedetails>)
			#<title>$title</title>
		}
		# first aired - show and ep
		elsif (m!^ *<FirstAired>([^<]*)</FirstAired>!){
			$first_aired = $1;
			
			#<aired>2000-12-31</aired>
		}
		# director - ep
		elsif (m!^ *<Director>\|?([^<]*?)\|?</Director>!){
			# need array or while for multiple <director>$director</director> entries?
			# try comma, as below?
			$director = $1;
			$director =~ s!^ *(.+?) *$!$1!g;
			$director =~ s!\|!, !g;
			#<director>$director</director>
		}
		# writer - ep
		elsif (m!^ *<Writer>\|?([^<]*?)\|?</Writer>!){
			$writer = $1;
			$writer =~ s!^ *(.+?) *$!$1!g;
			$writer =~ s!\|!, !g;
			#<credits>Writer</credits>
		}
		# actors 
		elsif (m!^ *<Actors>\|?([^<]*?)\|?</Actors>!){
			$actors = $1;
			$actors =~ s!^ *(.+?) *$!$1!g;
			$actors =~ s!\|!, !g;
			
			#<actor>
			#	<name>Little Suzie</name>
			#	<role>Pole Jumper/Dancer</role>
			#</actor>
		}
		# guests
		elsif (m!^ *<GuestStars>\|?([^<]*?)\|?</GuestStars>!){
			$actors = $1;
			$actors =~ s!^ *(.+?) *$!$1!g;
			$actors =~ s![\|:] ?!, !g;
		}
		elsif (m!^ *<Rating>([^<]*)</Rating>!){$rating="Rating....: $1<br>\t";}
		elsif (m!^ *<RatingCount>([^<]*)</RatingCount>!){$votes="Votes.....: $1<br>\t";}
		
		elsif (m!^ *<Overview>([^<]*)(?:</Overview>)?!){
			$plot = $1;
			$plot =~ s!&#13;$!!; # unknown char @ EOL 
			$plot =~ s! +! !g;
			$plot =~ s![\r\n]+!!g;
			
			# needs to wait
			#<plot>he best episode in the world</plot>
		}
		# for lines in between Overview open and close lines
		elsif (m!^(\w[^<>]+)$!){
			my $splot = $1;
			$splot =~ s!&#13;$!!; # unknown char @ EOL 
			$splot =~ s! +! !g;
			$plot .= $splot;
			$plot =~ s![\r\n]+!!g;
		}
		elsif (m!^([^<]*)</Overview>!){
			#my $splot = "<br>            $1";
			my $splot .= $1;
			$splot =~ s!&#13;$!!; # unknown char @ EOL 
			$splot =~ s! +! !g;
			$plot .= $splot;
			$plot =~ s![\r\n]+!!g;
		}
		
		# show
		elsif (m!^ *<Status>([^<]*)</Status>!){
			#<status>$1</status>
		}
		elsif (m!^ *<ContentRating>([^<]*)</ContentRating>!){
			#<mpaa>$1</mpaa>
		}
		elsif (m!^ *<Genre>\|?([^<]*?)\|?</Genre>!){
			$genre = $1;
			$genre =~ s! ?(.+?) ?$!$1!g;
			$genre =~ s!\|!, !g;
			#<genre>$genre</genre>
		}
		
		elsif (m!^ *<IMDB_ID>([^<]*)</IMDB_ID>!){ $IMDb = $1; }
		# ep screenshot - handled later
		elsif (m!^ *<filename>([^<]*)</filename>$!){
			if ($1){ $rec_tail = 'JPG'; }
		}
		# show poster (small) - ep listings don't have <poster>
		elsif (m!^ *<poster>([^<]+)</poster>$!){
			$rec_tail = "http://thetvdb.com/banners/_cache/$1";
			unless (-e "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id.jpg"){
				my $response = $user_agent->get($rec_tail, ':content_file' => "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id.jpg");
				unless ($response->is_success) {
					&Print ("Image ($1) fetch failed: ".$response->status_line.' (TV60)', 3, 0);
					$rec_tail = "http://thetvdb.com/banners/_cache/posters/$tvdb_id-1.jpg";
					$response = $user_agent->get($rec_tail, ':content_file' => "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id.jpg");
					if ($response->is_success) {
						&Print ("Alternate image fetch successful: posters/$tvdb_id-1.jpg (TV61)", 3, 0);
					}
					else { &Print ("Alternate image ($tvdb_id-1.jpg) fetch also failed: ".$response->status_line.' (TV62)', 1, 0); }
					
				}
			}
		}
		# some unused data fields
		#elsif (m!^ *?<Network>([^<]*)</Network>!){$net="Network...: $1<br>\t";}
		#elsif (m!^ *?<Airs_DayOfWeek>([^<]*)</Airs_DayOfWeek>!){$day="Day.......: $1<br>\t";}
		#elsif (m!^ *?<Airs_Time>([^<]*)</Airs_Time>!){$time="Time......: $1<br>\t";}
		#elsif (m!^ *?<Runtime>([^<]*)</Runtime>!){$run="Runtime...: $1 min<br>\t";}
		#elsif (m!^ *?<Language>([^<]*)</Language>!){$lang="Lang......: $1<br>\t";}
		
		elsif (m!^ *</Series>!){ # needs to be $ep_id for successive matches
			if ($first_aired){ $first_aired = "1st Aired.: $first_aired<br>\t"; }
			$ep_rec = "$title$first_aired$status$rated$genre$actors$rating$votes$plot$DateTime[2]$IMDb\n";
			$record .= "$ep_id\t$title$first_aired$status$rated$genre$actors$rating$votes$plot$DateTime[2]$IMDb\n";
			$count ++;
			# vars that need to be emptied
			$first_aired = ''; $plot = ''; $IMDb = ''; 
		}
		elsif (m!^ *</Episode>!){
			# skip all worthless ep titles and all specials (O season)... but this is used for ep info as well - not just ep titles
			# removed |Season|Episode|Chapter, needed for episode pages (won't be in db otherwise)
			# ... may want to keep Season, may want to remove ^0 - don't really know
			if ($title =~ m!^(TBA|TBD)!i or $ep_num =~m!^0!){ next; }
			#elsif ($title =~ m!^(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)!){ next; }
			elsif ($title) { 
				# ep title > full 'show ep num - ep title'
				#$title =~ s!Title\.\.\.\.\.: (.+)<br>\t!Title.....: $show $ep_num - $1<br>\t!;
				$title = "Title.....: $show $ep_num - $title<br>\t";
				# contains JPG if there's an image
				$rec_tail .= "/$tvdb_id/$s_id/$ep_id";
				#  datetime(JPG)/showid/seasonid/epid(ttnum added later)
				$rec_tail = "$DateTime[2]$rec_tail";
				# for date based ep num/match
				if ($episode =~ m!\d{2}-\d{2}-\d{2}!){ 
					unless ($first_aired){ $first_aired = '00-00-00'; }
					$ep_num = $first_aired; 
					$ep_num =~ s!^(20|19)!!; 
					
				}
				$first_aired = "1st Aired.: $first_aired<br>\t"; # needs to be after above
				# ep match record and image
				if ($ep_num eq $episode){ 
					if ($rec_tail =~ m!JPG/!){
						unless (-e "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id\_$ep_id.jpg"){
							my $url = "http://thetvdb.com/banners/episodes/$tvdb_id/$ep_id.jpg";
							my $response = $user_agent->get($url, ':content_file' => "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id\_$ep_id.jpg");
							unless  ($response->is_success) { &Print ("Image fetch failed: $response->status_line (TV63)", 1, 0); }
						}
					}
					$ep_rec = "$title$first_aired$director$writer$actors$rating$votes$plot$rec_tail$IMDb\n"; 
				}
# 				elsif (!$episode){
# 					$ep_rec .= "$title$first_aired$director$writer$actors$rating$votes$plot\n";
# 				}
				#else { $ep_rec = "$title$first_aired$director$writer$actors$rating$votes$plot$rec_tail$IMDb\n"; }
				$record .= "$ep_id $ep_num\t$title$first_aired$director$writer$actors$rating$votes$plot$rec_tail$IMDb\n"; }
				# vars that need to be emptied
				$rec_tail = '';
		}
		elsif (m!^ *</Data>! and !$record){ $record = 'No matches found'; }
	}
	return ($record, $tvdb_id, $count, $ep_rec);
}

sub PrintTvdb {
	my ($record, $count, $title, $episode, $tvdb_id, $edit, $re) = @_ ;
	my $imdb = '';
	$record =~ s!<br>\t?!\n!g;
	# multiple parent possibilities
	if ($count > 1){
		$record =~ s!(tt\d+)!Links.....: <A HREF=\"http://www.imdb.com/title/$1/\">IMDb</A>\n!g;
		$record =~ s!\w{3} \d{2} \d{4}!!g;
		$record =~ s!(\d+)\tTitle.....: ([^\n]+)!Title.....: [<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=$episode&amp;id=$1&amp;db=&amp;re=$re\">$2</a>]!g;
		$record = "Multiple matches found, please select one of the following titles:\n\n$record";
		$record = "<pre><font face=\"Monospace,Courier,Courier New\">$record</font></pre></td></tr><tr><td>";
	}
	# parent records only
	elsif ($record =~ s!(\w{3} \d{2} \d{4})(tt\d+)?$!!){ 
		if ($2){ $imdb = "&nbsp;&nbsp;<A HREF=\"http://www.imdb.com/title/$2/\">IMDb</A>&nbsp"; }
		#$record .= "Links.....: <A HREF=\"http://thetvdb.com/?tab=series&id=$tvdb_id\">TVDb</A>&nbsp;$imdb&nbsp;&nbsp;Record:&nbsp;<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=$episode&amp;id=$tvdb_id&amp;db=del&amp;re=$re\">delete</a>&nbsp;<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=$episode&amp;id=$tvdb_id&amp;db=up&amp;re=$re\">update</a>&nbsp;&nbsp;&nbsp;<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=&amp;id=$tvdb_id&amp;db=list&amp;re=$re\">Episode list</a>\n\n$1\n";
		$record .= "Links.....: <A HREF=\"http://thetvdb.com/?tab=series&id=$tvdb_id\">TVDb</A>&nbsp;$imdb&nbsp;&nbsp;Record:&nbsp;<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=$episode&amp;id=$tvdb_id&amp;db=up&amp;re=$re\">update</a>&nbsp;<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=$episode&amp;id=$tvdb_id&amp;db=del&amp;re=$re\">delete</a>\n\n$1\n";
		if (-e "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id.jpg"){
			$record = "<img SRC=\"$VAR{'PPWebUrl'}/data/tvdb/images/$tvdb_id.jpg\" style=\"float:right\; padding-right:50px;\"><pre><font face=\"Monospace,Courier,Courier New\">\n$record</font></pre><br clear=\"all\"></td></tr><tr><td>";
		}
		else { $record = "<pre><font face=\"Monospace,Courier,Courier New\">$record</font></pre></td></tr><tr><td>"; }
	}
	# episode records
	elsif ($episode and $record =~ s!(\w{3} \d{2} \d{4})(JPG)?/$tvdb_id/(\d+)/(\d+)(tt\d+)?$!!){
		my $ep_img;
		if ($2){ $ep_img = $tvdb_id.'_'.$4.'.jpg'; }
		if ($5){ $imdb = "&nbsp;&nbsp;<A HREF=\"http://www.imdb.com/title/$5/\">IMDb</A>&nbsp"; }
		#$record .= "Links.....: <A HREF=\"http://thetvdb.com/?tab=episode&amp;seriesid=$tvdb_id&amp;seasonid=$3&amp;id=$4\">TVDb</A>&nbsp;$imdb&nbsp;&nbsp;Record:&nbsp;<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=$episode&amp;id=$tvdb_id&amp;db=del&amp;re=$re\">delete</a>&nbsp;<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=$episode&amp;id=$tvdb_id&amp;db=up&amp;re=$re\">update</a>&nbsp;&nbsp;&nbsp;View:&nbsp;<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=&amp;id=$tvdb_id&amp;db=list&amp;re=$re\">list</a>&nbsp;<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=&amp;id=$tvdb_id&amp;db=&amp;re=$re\">parent</a>\n\n$1\n";
		$record .= "Links.....: <A HREF=\"http://thetvdb.com/?tab=episode&amp;seriesid=$tvdb_id&amp;seasonid=$3&amp;id=$4\">TVDb</A>&nbsp;$imdb&nbsp;&nbsp;View:&nbsp;<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=&amp;id=$tvdb_id&amp;db=list&amp;re=$re\">episodes</a>&nbsp;<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=&amp;id=$tvdb_id&amp;db=&amp;re=$re\">parent</a>\n\n$1\n";
		if ($ep_img and -e "$VAR{'PPWebDir'}/data/tvdb/images/$ep_img"){
			$record = "<img SRC=\"$VAR{'PPWebUrl'}/data/tvdb/images/$ep_img\" style=\"float:right\; padding-right:50px;\"><pre><font face=\"Monospace,Courier,Courier New\">\n$record</font></pre><br clear=\"all\"></td></tr><tr><td>";
		}
		elsif ($ep_img){
			require LWP::UserAgent;
			my $user_agent = LWP::UserAgent->new;
			$user_agent->agent("Mozilla/8.1");
			#my $url = "http://thetvdb.com/banners/episodes/$tvdb_id/$4.jpg";
			my $url = "http://thetvdb.com/banners/episodes/$ep_img";
			$url =~ s!$tvdb_id\_!$tvdb_id/!;
			my $response = $user_agent->get($url, ':content_file' => "$VAR{'PPWebDir'}/data/tvdb/images/$ep_img");
			if  ($response->is_success) { 
				&Print ("Got TVDb episode image for $title $episode (TV73)", 4, 0);
				$record = "<img SRC=\"$VAR{'PPWebUrl'}/data/tvdb/images/$ep_img\" style=\"float:right\; padding-right:50px;\"><pre><font face=\"Monospace,Courier,Courier New\">\n$record</font></pre><br clear=\"all\"></td></tr><tr><td>";
			}
			elsif (-e "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id.jpg"){
				$record = "<img SRC=\"$VAR{'PPWebUrl'}/data/tvdb/images/$tvdb_id.jpg\" style=\"float:right\; padding-right:50px;\"><pre><font face=\"Monospace,Courier,Courier New\">\n$record</font></pre><br clear=\"all\"></td></tr><tr><td>"; 
			}
		}
		elsif (-e "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id.jpg"){
			$record = "<img SRC=\"$VAR{'PPWebUrl'}/data/tvdb/images/$tvdb_id.jpg\" style=\"float:right\; padding-right:50px;\"><pre><font face=\"Monospace,Courier,Courier New\">\n$record</font></pre><br clear=\"all\"></td></tr><tr><td>"; 
		}
		else {
			$record = "<pre><font face=\"Monospace,Courier,Courier New\">\n$record</font></pre><br clear=\"all\"></td></tr><tr><td>"; 
		}
	}
	elsif ($record eq 'No matches found' and $edit){
		$record = "<pre><font face=\"Monospace,Courier,Courier New\">No matches found, try [<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=$episode&amp;id=&amp;db=$edit&amp;re=$re\">$edit</a>]</font></pre></td></tr><tr><td>";
	}
	elsif ($record eq 'No matches found' and $title =~ m!(.+) And (.+)$!){
		$record = "<pre><font face=\"Monospace,Courier,Courier New\">No matches found, try [<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=$episode&amp;id=&amp;db=$1\%20$2&amp;re=$re\">$1 $2</a>]</font></pre></td></tr><tr><td>";
	}
	elsif ($record eq 'No matches found' and $title =~ m!(.+) [^ ]+$!){
		$record = "<pre><font face=\"Monospace,Courier,Courier New\">No matches found, try [<a href=\"$VAR{'DbCgi'}?do=tvdb&amp;nt=$title&amp;ep=$episode&amp;id=&amp;db=$1&amp;re=$re\">$1</a>]</font></pre></td></tr><tr><td>";
	}
	elsif (-e "$VAR{'PPWebDir'}/data/tvdb/images/$tvdb_id.jpg"){
		$record = "<img SRC=\"$VAR{'PPWebUrl'}/data/tvdb/images/$tvdb_id.jpg\" style=\"float:right\; padding-right:50px;\"><pre><font face=\"Monospace,Courier,Courier New\">\n$record</font></pre><br clear=\"all\"></td></tr><tr><td>";
	}
	else { $record = "<pre><font face=\"Monospace,Courier,Courier New\">$record</font></pre></td></tr><tr><td>"; }
	
	return $record;
}
	
	# api wiki http://www.thetvdb.com/wiki/index.php/Programmers_API
	# get mirrors N/A?: http://www.thetvdb.com/api/D192BBDD2E810B5C/mirrors.xml
	
	# get show id       http://thetvdb.com/api/GetSeries.php?seriesname=[show name]
	# get desc          http://thetvdb.com/api/$api/series/[show id]
	# http://thetvdb.com/api/D192BBDD2E810B5C/series/248789/en.xml
	# get all eps       http://thetvdb.com/api/$api/series/[show id]/all/en.zip
	# get season poster http://thetvdb.com/banners/_cache/posters/[show id]-[season].jpg
	
	# get episode info  http://thetvdb.com/api/$api/series/[show id]/default/[season#]/[episode#]/en.xml
	# or                http://thetvdb.com/api/$api/episode/[episode id](/en.xml)
	
	# get episode image http://thetvdb.com/banners/episodes/[show id]/[episode id].jpg
	#http://thetvdb.com/api/D192BBDD2E810B5C/series/164541
	#http://thetvdb.com/api/GetEpisodeByAirDate.php?apikey=D192BBDD2E810B5C&seriesid=71256&airdate=12-03-14


1;